<script lang="ts" setup name="AbnormalResultStatistics">
import {SeleteData} from '@/api/config'
import {getAllCategoryList} from '@/api/physicalExaminationManager/majorCategories'
import {getTeamListAll} from '@/api/publicHealthExamination/communitySettings'
import {SearchButton, SearchFromItem} from '@/components/dTable/dHeader'
import dHeader from '@/components/dTable/dHeader.vue'
import AbnormalResultRanking from './components/abnormalResultRanking.vue'
import PersonTimeStatistics from './components/personTimeStatistics.vue'
import {Number_3} from '@/util/common'
import {FormRules} from 'element-plus'
import {computed, onActivated, onDeactivated, reactive, ref} from 'vue'

const resultRankingRef = ref()
const personTimeRef = ref()
// 社区下拉
const selectTeamLsit = ref<Array<SeleteData>>([])
// 性别下拉
const selectGanderList = ref<Array<SeleteData>>([
  {label: '男', value: '男'},
  {label: '女', value: '女'}
])
// 体检大类下拉
const selectCheckupCategory = ref<Array<SeleteData>>([])

// 头部搜索表单
const searchFromItems = ref<Array<SearchFromItem>>([
  {label: '', type: 'slot', slotName: 'phyDate', prop: 'phyDate', class: {'statistics-date': true}},
  {label: '社区', placeholder: '请选择社区', type: 'selete', seleteData: selectTeamLsit.value, prop: 'teamId', changeSubmit: true},
  {label: '体检大类', placeholder: '请选择体检大类', type: 'selete', seleteData: selectCheckupCategory.value, prop: 'TestCategory', changeSubmit: true},
  {label: '性别', placeholder: '请选择性别', type: 'selete', seleteData: selectGanderList.value, prop: 'gender', changeSubmit: true},
  {label: '年龄段', placeholder: '请输入年龄段', prop: 'ageStage', type: 'slot', slotName: 'ageStage'}
])

// 按钮搜索配置
const serachButtons = ref<Array<SearchButton>>([{type: 'search'}, {type: 'clear'}])

// 头部搜索表单
const searchFromData = reactive({
  phyDate: '',
  minAge: '',
  maxAge: '',
  year: '',
  month: ''
})

//判断年龄
const ageStage = (_rule, _value: string, callback) => {
  if (!searchFromData.minAge && !searchFromData.maxAge) {
    callback()
    return
  }
  const vLeft = searchFromData.minAge
  const vRight = searchFromData.maxAge
  if (vLeft && !Number_3.test(searchFromData.minAge || '')) {
    callback(new Error('不超过3位的正整数!'))
  } else if (vRight && !Number_3.test(searchFromData.maxAge || '')) {
    callback(new Error('不超过3位的正整数!'))
  } else {
    callback()
  }
}

// 判断年龄前后大小
const ageStageBigger = (_rule, _value: string, callback) => {
  const vLeft = searchFromData.minAge
  const vRight = searchFromData.maxAge
  if (vLeft && vRight && Number(vLeft) > Number(vRight)) {
    return callback(new Error('起始值应小于结束值'))
  } else {
    return callback()
  }
}

// 头部搜索表单校验
const searchFromRules = reactive<FormRules>({
  ageStage: [
    {validator: ageStage, trigger: ['change', 'blur']},
    {validator: ageStageBigger, trigger: ['change', 'blur']}
  ]
})

// 年份选择
const yearOptions = computed(() => {
  // 获取当前年份
  const year = new Date().getFullYear()
  const yearArr: Array<number> = []
  for (let i = year; i >= 2020; i--) {
    yearArr.unshift(i)
  }
  return yearArr
})
// 月份选择
const monthOptions = computed(() => {
  let monthArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
  // 当前月
  const month = new Date().getMonth() + 1
  // 如果是当前年份，月份截止到当前月
  if (searchFromData.year + '' === new Date().getFullYear() + '') {
    monthArr = monthArr.slice(0, month)
  } else {
    monthArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
  }
  return monthArr
})

/**
 * @description: 查询数据
 * @return {*}
 */
const searchData = () => {
  console.log('搜索')
}

//搜索事件
const onSubmit = () => {
  searchData()
}

//清除搜索栏数据事件
const clearForm = () => {
  searchFromData.phyDate = ''
  searchData()
}

//清空搜索表单事件
const onFormClear = () => {
  clearForm()
}

/**
 * @description: 年份改变
 * @return {*}
 */
const onYearChange = () => {
  searchFromData.month = '' // 清空月份
  onSubmit()
}

/**
 * @description: 获取社区下拉
 * @return {*}
 */
const getTeamSelect = () => {
  selectTeamLsit.value.length = 0
  getTeamListAll().then((res) => {
    res.data.data?.length &&
      res.data.data.forEach((item) => {
        selectTeamLsit.value.push({label: item.name, value: item.id || ''})
      })
  })
}

/**
 * @description: 获取体检大类下拉
 * @return {*}
 */
const getCheckupCategoryList = () => {
  selectCheckupCategory.value.length = 0
  getAllCategoryList().then((res) => {
    const {data} = res.data
    data.length &&
      data.forEach((item) => {
        selectCheckupCategory.value.push({label: item.categoryName, value: item.categoryName || ''})
      })
  })
}

/**
 * @description: 重新加载大小
 * @return {*}
 */
const onReset = () => {
  resultRankingRef.value && resultRankingRef.value?.onReset()
  personTimeRef.value && personTimeRef.value?.onReset()
}

onActivated(() => {
  getTeamSelect() // 社区下拉
  searchData() // 查询数据
  getCheckupCategoryList() // 体检大类下拉
  window.addEventListener('resize', onReset)
})

onDeactivated(() => {
  // 销毁
  window.removeEventListener('resize', onReset)
})
</script>
<template>
  <div class="abnormal-result-statistics-page d-common-full">
    <div class="abnormal-result-statistics-header">
      <d-header
        :search-form-data="searchFromData"
        :search-rules="searchFromRules"
        :search-form-items="searchFromItems"
        :search-buttons="serachButtons"
        :search-from-justify="'flexStart'"
        :search-from-full="true"
        @form-submit="onSubmit"
        @form-clear="onFormClear"
      >
        <template #phyDate>
          <div>
            <el-row :gutter="5">
              <el-col :span="10">
                <el-select v-model="searchFromData.year" clearable placeholder="请选择年" filterable @change="onYearChange">
                  <el-option v-for="item in yearOptions" :key="item" :label="item" :value="item" />
                </el-select>
              </el-col>
              <el-col :span="2">
                年
              </el-col>
              <el-col :span="10">
                <el-select v-model="searchFromData.month" clearable placeholder="请选择月" filterable @change="onSubmit">
                  <el-option v-for="item in monthOptions" :key="item" :label="item" :value="item" />
                </el-select>
              </el-col>
              <el-col :span="2">
                月
              </el-col>
            </el-row>
          </div>
        </template>
        <template #ageStage>
          <div>
            <el-row :gutter="5">
              <el-col :span="11">
                <el-input v-model="searchFromData.minAge" clearable placeholder="最小年龄" @keyup.enter="onSubmit" />
              </el-col>
              <el-col :span="2">
                ~
              </el-col>
              <el-col :span="11">
                <el-input v-model="searchFromData.maxAge" clearable placeholder="最大年龄" @keyup.enter="onSubmit" />
              </el-col>
            </el-row>
          </div>
        </template>
      </d-header>
    </div>
    <div class="abnormal-result-statistics-body">
      <div class="statistics-box">
        <p>异常结果前十排行</p>
        <div class="statistics-echart">
          <abnormal-result-ranking ref="resultRankingRef" />
        </div>
      </div>
      <div class="statistics-box">
        <p>体检人次统计</p>
        <div class="statistics-echart">
          <person-time-statistics ref="personTimeRef" />
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="less" scoped>
.abnormal-result-statistics-page {
  padding: 14px;
  background: var(--d-color-grey-2);
}
.abnormal-result-statistics-header {
  background: var(--d-color-white);
  padding: 12px 20px;
  box-shadow: 0px 0px 3px 1px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  :deep(.d-table-from-con) {
    margin: 0;
    padding: 0;
  }
}

:deep(.statistics-date) {
  .el-form-item__content {
    margin: 0 !important;
    width: 250px;
  }
  .el-select {
    input {
      text-align: center;
    }
  }
}
.abnormal-result-statistics-body {
  margin-top: 18px;
  display: flex;
  gap: 16px;
  justify-content: space-between;
  .statistics-box {
    width: 100%;
    border-radius: 4px;
    box-shadow: 0px 0px 3px 1px rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    p {
      margin: 0;
      height: 40px;
      padding: 10px 20px;
      border-radius: 4px 4px 0px 0px;
      background: #f6f6f6;
      color: #333333;
    }
    .statistics-echart {
      aspect-ratio: 2/1;
      background: var(--d-color-white);
      border-radius: 0px 0px 4px 4px;
    }
  }
}
</style>
